#include "PWMDriver.h"



static void PWM_Init(uint16_t PWM_Freq,uint16_t PWM_Duty)
{
	GPIO_InitPara GPIO_InitStructure;
	TIMER_BaseInitPara  TIM_TimeBaseStructure;
	TIMER_OCInitPara    TIM_OCInitStructure;
	
	RCC_APB1PeriphClock_Enable(RCC_APB1PERIPH_TIMER4, ENABLE);
	RCC_APB2PeriphClock_Enable(RCC_APB2PERIPH_GPIOB , ENABLE);
	
  /*GPIOB Configuration: TIMER4 CH3*/
	GPIO_InitStructure.GPIO_Pin   = GPIO_PIN_8;
	GPIO_InitStructure.GPIO_Mode  = GPIO_MODE_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_SPEED_50MHZ;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	TIM_TimeBaseStructure.TIMER_Prescaler     = 1080-1;
	TIM_TimeBaseStructure.TIMER_Period        = 500-1;
	TIM_TimeBaseStructure.TIMER_ClockDivision = 0;
	TIM_TimeBaseStructure.TIMER_CounterMode   = TIMER_COUNTER_UP; 
	TIMER_BaseInit(TIMER4, &TIM_TimeBaseStructure); 

	/* PWM1 MODE configuration: TIMER4 Channel3 */
	TIM_OCInitStructure.TIMER_OCMode      = TIMER_OC_MODE_PWM1;
	TIM_OCInitStructure.TIMER_OutputState = TIMER_OUTPUT_STATE_ENABLE;
	TIM_OCInitStructure.TIMER_Pulse       = 0;
	TIM_OCInitStructure.TIMER_OCPolarity  = TIMER_OCN_POLARITY_HIGH;

	TIMER_OC3_Init(TIMER4, &TIM_OCInitStructure);
	TIMER_OC3_Preload(TIMER4, TIMER_OC_PRELOAD_ENABLE);

	TIMER_CARLPreloadConfig(TIMER4, ENABLE);
	TIMER_Enable(TIMER4, ENABLE);
}


static void PWM_Write(PWMType Type,uint16_t Param)
{
	
	if(Type == PWM_Freq)
	{
		TIMER4->CARL = Param;
	}
	else if(Type == PWM_Duty)
	{
		TIMER_Compare3Config(TIMER4 ,Param);
	}
	else
	{
		#ifdef DEBUG_PWM
			printf("Write PWM Error,But PWM Type Exit\n");
		#endif
	}

}



static uint16_t PWM_Read(PWMType Type)
{
		if(Type == PWM_Freq)
		{
			return TIMER4->CARL;
		}
		else if(Type == PWM_Duty)
		{
			return TIMER4->CHCC3;
		}
		else 
		{
			#ifdef DEBUG_PWM
				printf("Read PWM Error,But PWM Type Exit\n");
			#endif
			return 0;
		}

}

Flow_PWMDrv PWM_Buzzer = {
														.Init = PWM_Init,
														.Write = PWM_Write,
														.Read = PWM_Read

												 };
